package com.wst.system.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.wst.system.security.IsAdmin;
import com.wst.system.security.IsSecurity;
import com.wst.system.server.entity.enm.SysFilePermission;
import com.wst.system.server.entity.vo.ManyDataVo;
import com.wst.system.util.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wst.system.config.exception.GlobalExcetion;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.Serializable;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.wst.system.server.service.SysFileService;
import com.wst.system.server.entity.SysFile;
import com.wst.system.server.entity.vo.SysFileVo;
import com.wst.system.server.entity.vo.PageSearchVo;
import org.springframework.validation.annotation.Validated;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.wst.system.server.entity.vo.DelManyDataVo;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletResponse;


/**
 * <p>
 * 文件表 前端控制器
 * </p>
 *
 * @author X.I.O
 * @since 2025-02-27
 */

@RestController
@Api(tags = {"文件表的服务类"})
@RequestMapping("/sys-file")
public class SysFileController  {

        @Autowired
        private SysFileService sysFileService;


        @PostMapping("/saveorupdate")
        @ApiOperation(value = "文件表的新增/更新接口",notes = "文件表的新增接口")
        public JSONObject save(@RequestBody @Validated SysFileVo sysFileVo) throws GlobalExcetion{
                sysFileService.saveOrUpdateSysFile(sysFileVo);
            return ResultUtil.successInfo("操作成功");
        }




        @DeleteMapping("/delbyid")
        @ApiOperation(value = "文件表的删除接口",notes = "文件表的删除接口")
        public JSONObject delete(@RequestParam("id") Serializable id) throws GlobalExcetion{
            boolean flag = sysFileService.removeById(id);
            if(flag){
                return ResultUtil.successInfo("删除成功");
            }else {
                return ResultUtil.errorInfo("删除失败");
            }
        }

        @PostMapping("/del/batch")
        @ApiOperation(value = "文件表的批量删除接口",notes = "文件表的批量删除接口")
        public JSONObject deleteBatch(@RequestBody DelManyDataVo vo) throws GlobalExcetion {
            boolean flag =  sysFileService.removeByIds(vo.getIds());
            if(flag){
                return ResultUtil.successInfo("删除成功");
            }else {
                return ResultUtil.errorInfo("删除失败");
            }
        }

        @PostMapping("/batch/public")
        public JSONObject batchPublic(@RequestBody @Validated ManyDataVo vo) throws GlobalExcetion{
            Integer uid=SecurityUtil.getUserId();
            sysFileService.updateBatchPermession(vo.getIds(),SysFilePermission.PUBLIC.getPermissionCode().toString(),String.valueOf(uid));
            return ResultUtil.successInfo();
        }


        @GetMapping("/getall")
        @ApiOperation(value = "文件表的获取全部接口",notes = "文件表的获取全部接口")
        public JSONObject findAll() throws GlobalExcetion {
            List<SysFile> list= sysFileService.list();
            return ResultUtil.successInfo(list);
        }

        @GetMapping("/getbyid")
        @ApiOperation(value = "文件表的获取一个接口",notes = "文件表的获取一个接口")
        public JSONObject findOne(@RequestParam("id") Serializable id) throws GlobalExcetion {
            SysFile data= sysFileService.getById(id);
            return ResultUtil.successInfo(data);
        }

    @PostMapping("/page")
    @ApiOperation(value = "文件表的分页接口",notes = "文件表的分页接口")
    public JSONObject findPage(@RequestBody @Validated PageSearchVo pageSearchVo) throws GlobalExcetion {
        IPage<SysFile> data=sysFileService.page(pageSearchVo);
        return ResultUtil.successInfoTable(data.getTotal(),data.getRecords());
    }

    @Value("${upload.dir}")
    private String uploadDir; // 自定义上传目录

    @Value("${upload.privateKey}")
    private String privateKey;

    @GetMapping("/getfilepermission")
    public JSONObject getFilePermission(){
        JSONArray array=new JSONArray();
        SysFilePermission[] sysFilePermissions=SysFilePermission.values();
        for(SysFilePermission sysFilePermission:sysFilePermissions){
            JSONObject object=new JSONObject();
            object.put("label",sysFilePermission.getPermissionName());
            object.put("value",sysFilePermission.getPermissionCode());
            array.add(object);
        }
        return ResultUtil.successInfo(array);
    }

    @PostMapping("/upload")
    public JSONObject handleFileUpload(@RequestParam("file") MultipartFile file,
                                       @RequestParam("groupId")String groupId) throws Exception {
        if(!StringUtils.isNotBlank(groupId)){
            return ResultUtil.errorInfo("groupId 不得为空");
        }
        SysFile sysFile=sysFileService.uploadFile(file,groupId);
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("id",sysFile.getId());
        jsonObject.put("url","/sys-file/donload?id="+sysFile.getId());
        jsonObject.put("filename",sysFile.getFileName());
        return ResultUtil.successInfo(jsonObject);
    }



    @GetMapping("donload")
    public void donload(@RequestParam("id")String id,
                        @RequestParam(value = "code",required = false)String code,
                        HttpServletResponse response) throws Exception {
        SysFile sysFile=sysFileService.getById(id);
        if(sysFile==null){
            throw new GlobalExcetion(1,"文件不存在");
        }
        Integer userId=SecurityUtil.getUserId();
        if(sysFile.getFilePermission()!=null){
            if(sysFile.getFilePermission().equals(String.valueOf(SysFilePermission.PUBLIC.getPermissionCode()))){

            }else if(sysFile.getFilePermission().equals(String.valueOf(SysFilePermission.PRIVATE.getPermissionCode()))){
                if(!sysFile.getFileUid().equals(String.valueOf(userId))){
                    throw new GlobalExcetion(1,"私有文件,您没有访问权限");
                }
            }else if(sysFile.getFilePermission().equals(String.valueOf(SysFilePermission.ENCRYPT.getPermissionCode()))){
                if(code==null){
                    throw new GlobalExcetion(1,"加密文件,需要填写验证码");
                }
                if(!code.equals(sysFile.getCode())){
                    throw new GlobalExcetion(1,"加密文件,验证码错误");
                }
            }
        }
        //文件未加密
        if(sysFile.getIsEncrypt()==0){
            byte[] bytes=FileUtils.getUploadFileByPath(sysFile.getFilePath());
            FileUtils.donload(bytes,sysFile.getFileName(),response);
        }else {
            AESFileUtil fileDESUtil = new AESFileUtil(sysFile.getCode());
            byte[] bytes=fileDESUtil.decrypt(sysFile.getFilePath());
            FileUtils.donload(bytes,sysFile.getFileName(),response);
        }
    }


    @IsSecurity(isSecurity = false)
    @GetMapping("/res/donload")
    public void resDonload(@RequestParam("pk")String pk,
                        @RequestParam("es")String es,
                        HttpServletResponse response) throws Exception {
        JSONObject jsonObject=null;
        try {
            jsonObject =TextEncryptUtils.decryptText(es,pk,this.privateKey);
        }catch (Exception e){
           throw new GlobalExcetion(1,"文件不存在");
        }
        if(jsonObject!=null){
            Long expireTime=jsonObject.getLong("expire_time");
            long currentTime=System.currentTimeMillis();
            System.out.println(expireTime);
            if(expireTime > 0 &&  currentTime>expireTime){
                throw new GlobalExcetion(1,"文件链接已过期");
            }
            Integer id=jsonObject.getInteger("id");
            SysFile sysFile=sysFileService.getById(id);
            if(sysFile==null){
                throw new GlobalExcetion(1,"文件不存在");
            }
            if(sysFile.getFilePermission()==null || !sysFile.getFilePermission().equals(String.valueOf(SysFilePermission.PUBLIC.getPermissionCode()))){
                throw new GlobalExcetion(1,"非公开文件，无法访问");
            }
            try {
                if(sysFile.getIsEncrypt()==0){
                    byte[] bytes=FileUtils.getUploadFileByPath(sysFile.getFilePath());
                    FileUtils.donload(bytes,sysFile.getFileName(),response);
                }else {
                    AESFileUtil fileDESUtil = new AESFileUtil(sysFile.getCode());
                    byte[] bytes=fileDESUtil.decrypt(sysFile.getFilePath());
                    FileUtils.donload(bytes,sysFile.getFileName(),response);
                }
            }catch (Exception e){
                sysFileService.removeBySha256Md5(sysFile.getFileSha256(),sysFile.getFileMd5());
            }
        }
    }



}

